layui.define(['table', 'form', 'upload', 'admin'], function (exports) {
    var $ = layui.$
        , table = layui.table
        , form = layui.form
        , upload = layui.upload
        , admin = layui.admin;


    table.on("sort(LAY-user-manage)", function (obj) {
        table.reload("LAY-user-manage", {
            initSort: obj,
            where: {
                field: obj.field, //排序字段   在接口作为参数字段  field order
                order: obj.type, //排序方式   在接口作为参数字段  field order
            },
        });
    });

    // 专家列表
    table.render({
        elem: '#LAY-expert-manage'
        , url: '/admin/expert/getlist'
        , cols: [[
            {field: 'id', width: 80, title: 'ID', sort: true, fixed: true}
            , {field: 'user_id', width: 100, title: '用户ID', fixed: true}
            , {field: 'nick_name', title: '专家昵称', width: 150}
            , {
                field: '', title: '头像', width: 80, templet: function (d) {
                    return '<img style="display: inline-block;height: 100%;" src= "' + d.profile + '" layadmin-event="iconPreview" value= "' + d.profile + '">';
                }
            }
            , {field: 'resume', title: '简介', width: 150}
            , {
                field: '', title: '专家等级', width: 100, templet: function (d) {
                    switch (d.grade) {
                        case 1:
                            return '初级专家';
                        case 2:
                            return '中级专家';
                        case 3:
                            return '高级专家';
                        default:
                            return '';
                    }
                }
            }
            , {
                field: '', title: '热门专家', width: 100, templet: function (d) {
                    return d.is_logicians == 1 ? '是' : '否'
                }
            }
            , {field: 'attention_count', title: '关注人数', width: 100}
            , {field: 'fans_count', title: '粉丝数', width: 100}
            , {field: 'plan_count', title: '累计发布', width: 100}
            , {field: 'plan_done_count', title: '已开奖', width: 100}
            , {field: 'win_times', title: '赢', width: 100, sort: true}
            , {field: 'flat_times', title: '走', width: 100, sort: true}
            , {field: 'lost_times', title: '输', width: 100, sort: true}
            , {
                field: 'win_rate', title: '胜率', width: 120, sort: true, templet: function (d) {
                    if (d.plan_done_count >= 10) {
                        return '10中' + d.win_rate;
                    }
                    return d.plan_done_count + '中' + d.win_rate
                }
            }
            , {field: 'profit_rate', title: '回报率', width: 100, sort: true}
            , {
                field: 'serial_win', title: '连红', width: 100, sort: true, templet: function (d) {
                    return d.serial_win + '连红'
                }
            }
            , {
                field: '', title: '创建人', width: 120, templet: function (d) {
                    return d.admin ? d.admin.name : '';
                }
            }
            , {field: 'create_time', width: 180, title: '创建日期'}

            , {title: '操作', width: 120, align: 'center', fixed: 'right', toolbar: '#table-expertlist'}
        ]]
        , page: true
        , limit: 20
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true
    });

    //监听工具条
    table.on('tool(LAY-expert-manage)', function (obj) {
        if (obj.event === 'edit') {
            var index = layer.open({
                type: 2
                , title: '编辑专家信息'
                , content: '/admin/expert/edit?id=' + obj.data.id
                , maxmin: true
                , area: ['700px', '450px']
            });
        }

    });

    form.on('submit(expert-add)', function (obj) {
        //提交
        admin.req({
            url: '/admin/expert/add_post'
            , data: obj.field
            , success: function (res) {
                if (res.code == 0) {
                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                    parent.layer.msg(res.msg, {icon: 1});
                    parent.layui.table.reload('LAY-expert-manage');
                }
            }
        });
        return false;
    });

    form.on('submit(expert-edit)', function (obj) {
        //提交
        admin.req({
            url: '/admin/expert/edit_post'
            , data: obj.field
            , success: function (res) {
                if (res.code == 0) {
                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                    parent.layer.msg(res.msg, {icon: 1});
                    parent.layui.table.reload('LAY-expert-manage');
                }
            }
        });
        return false;
    });


    //上传头像
    var iconSrc = $('#LAY_iconSrc');
    var iconPreview = $('#LAY_iconPreview');
    upload.render({
        url: '/admin/index/noOperation'
        , elem: '#LAY_iconUpload'
        , auto: true
        , choose: function (obj) {
            layer.load();
            var choosefile;
            obj.preview(function (index, file, result) {
                choosefile = file;
            });
            admin.req({
                url: '/admin/index/signForCos'
                , success: function (res) {
                    if (res.code == 0) {
                        var cos = new COS({
                            getAuthorization: function (options, callback) {
                                var credentials = res.data.credentials;
                                callback({
                                    TmpSecretId: credentials.tmpSecretId,
                                    TmpSecretKey: credentials.tmpSecretKey,
                                    XCosSecurityToken: credentials.sessionToken,
                                    ExpiredTime: res.data.expiredTime
                                });
                            }
                        });
                        cos.putObject({
                            Bucket: res.data.bucket,
                            Region: res.data.region,
                            Key: 'images/' + res.data.filename + choosefile.name,
                            Body: choosefile,
                        }, function (err, data) {
                            layer.closeAll('loading');
                            if (err) {
                                console.log(err);
                                layer.msg("上传失败", {icon: 5});
                            } else {
                                if (data.statusCode == 200) {
                                    iconSrc.val("https://" + data.Location);
                                    iconPreview.attr("value", iconSrc.val());
                                } else {
                                    layer.msg("图片上传失败", {icon: 5});
                                }
                            }
                        });
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.msg, {icon: 5});
                    }
                },
                complete: function () {
                    layer.closeAll('loading');
                }
            })
        }
    });

    //查看头像
    admin.events.iconPreview = function (othis) {
        var src = othis.attr("value");
        if (!src) {
            src = iconSrc.val();
        }
        layer.photos({
            photos: {
                "title": "查看" //相册标题
                , "data": [{
                    "src": src //原图地址
                }]
            }
            , shade: 0.01
            , closeBtn: 1
            , anim: 5
        });
    };


    // 方案列表
    table.render({
        elem: '#LAY-expert-plan-manage'
        , url: '/admin/expert/get_plan_list'
        , cols: [[
            {field: 'id', width: 80, title: 'ID', sort: true, fixed: true}
            , {field: 'title', title: '标题', minWidth: 150}
            , {
                field: '', title: '专家名称', width: 120, templet: function (d) {
                    return d.expert ? d.expert.nick_name : '';
                }
            }
            , {
                field: '', title: '赛事标题', width: 150, templet: function (d) {
                    return d.match_schedule ? d.match_schedule.comp : '';
                }
            }
            , {
                field: '', title: '联赛分类', width: 100, templet: function (d) {
                    switch (d.sport_id) {
                        case 1:
                            return '足球';
                            break;
                        case 2:
                            return '篮球';
                            break;
                        default:
                            return '';
                    }
                }
            }
            , {
                field: '', title: '主队名称', width: 150, templet: function (d) {
                    return d.match_schedule ? d.match_schedule.home : '';
                }
            }
            , {
                field: '', title: '客队名称', width: 150, templet: function (d) {
                    return d.match_schedule ? d.match_schedule.away : '';
                }
            }
            , {
                field: '', title: '比赛时间', width: 180, templet: function (d) {
                    return d.match_schedule ? formatTimeStamp(d.match_schedule.match_time) : '';
                }
            }
            // , {field: 'home_score', title: '主队比分', width: 100}
            // , {field: 'away_score', title: '客队比分', width: 100}
            , {
                field: '', title: '玩法类型', width: 180, templet: function (d) {
                    var html = '';
                    if (d.sport_id == 1) {
                        switch (d.play_type) {
                            case 1:
                                html = '欧指';
                                break;
                            case 2:
                                html = '让球';
                                break;
                            case 3:
                                html = '大小';
                                break;
                            default:
                                return '';
                        }
                    } else {
                        switch (d.play_type) {
                            case 1:
                                html = '欧指';
                                break;
                            case 2:
                                html = '让分';
                                break;
                            case 3:
                                html = '总分';
                                break;
                            default:
                                return '';
                        }
                    }
                    if (d.expert_play_name_str) {
                        html += "（" + d.expert_play_name_str + "）"
                    }
                    return html;
                }
            }
            , {field: 'recommend_str', title: '专家预测', width: 120}
            , {
                field: '', title: '付费类型', width: 120, templet: function (d) {
                    switch (d.fee_type) {
                        case 0:
                            return '免费';
                        case 1:
                            return '付费钻石';
                        case 2:
                            return '付费宝石';
                    }
                    return '免费';
                }
            }
            , {field: 'fee_pay', title: '价格', width: 100}
            , {field: 'content', title: '竞猜内容', width: 200}
            , {
                field: '', title: '方案结果', width: 120, templet: function (d) {
                    switch (d.is_win) {
                        case 0:
                            return '未开奖';
                        case 1:
                            return '未猜中';
                        case 2:
                            return '已猜中';
                        case 3:
                            return '走';
                    }
                    return '未开奖';
                }
            }
            , {field: 'create_time', width: 180, title: '发布时间', sort: true}
            , {field: 'awards_time', width: 180, title: '开奖时间', sort: true}
            , {title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#table-expertlist'}
        ]]
        , page: true
        , limit: 20
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true
    });

    //监听工具条
    table.on('tool(LAY-expert-plan-manage)', function (obj) {
        if (obj.event === 'edit') {
            var index = layer.open({
                type: 2
                , title: '编辑有料帖子'
                , content: '/admin/expert/plan_edit?id=' + obj.data.id
                , maxmin: true
            });
            layer.full(index);
        } else if (obj.event === 'del') {
            return layer.msg('没有相关操作', {icon: 1});
            layer.confirm('确定要删除吗？', function (index) {
                layer.load();
                admin.req({
                    url: '/admin/expert/plan_del?id=' + obj.data.id
                    , data: {"id": obj.data.id}
                    , success(res) {
                        layer.closeAll('loading');
                        if (res.code == 0) {
                            table.reload("LAY-expert-plan-manage");
                            layer.msg(res.msg, {icon: 1});
                        }
                    },
                    complete: function () {
                        layer.closeAll('loading');
                    }
                });
            });
        } else if (obj.event === 'setWin') {
            var index = layer.open({
                type: 2
                , title: '设置开奖'
                , content: '/admin/expert/plan_set_win?id=' + obj.data.id
                , maxmin: true
                , area: ['450px', '210px']
            });
        }
    });

    // 添加方案
    form.on('submit(expert-plan-add)', function (obj) {
        layer.load();
        //提交
        admin.req({
            url: '/admin/expert/plan_add_post'
            , data: obj.field
            , success: function (res) {
                layer.closeAll('loading');
                if (res.code == 0) {
                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                    parent.layer.msg(res.msg, {icon: 1});
                    parent.layui.table.reload('LAY-expert-plan-manage');
                }
            },
            complete: function () {
                layer.closeAll('loading');
            }
        });
        return false;
    });

    // 编辑方案
    form.on('submit(expert-plan-edit)', function (obj) {
        layer.load();
        admin.req({
            url: '/admin/expert/plan_edit_post'
            , data: obj.field
            , success: function (res) {
                layer.closeAll('loading');
                if (res.code == 0) {
                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                    parent.layer.msg(res.msg, {icon: 1});
                    parent.layui.table.reload('LAY-expert-plan-manage');
                }
            },
            complete: function () {
                layer.closeAll('loading');
            }
        });
        return false;
    });

    // 设置输赢
    form.on('submit(expert-plan-set_win)', function (obj) {
        //提交
        layer.load();
        admin.req({
            url: '/admin/expert/plan_set_win_post'
            , data: obj.field
            , success: function (res) {
                layer.closeAll('loading');
                if (res.code == 0) {
                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                    parent.layer.msg(res.msg, {icon: 1});
                    parent.layui.table.reload('LAY-expert-plan-manage');
                }
            }
            , complete: function () {
                layer.closeAll('loading');
            }
        });
        return false;
    });

    exports('expert', {})
});


function formatTimeStamp(time_stamp) {
    const time = new Date(time_stamp * 1000);
    const Y = time.getFullYear();
    const M = (time.getMonth() + 1).toString().padStart(2, "0");
    const D = time.getDate().toString().padStart(2, "0");
    const h = time.getHours().toString().padStart(2, "0");
    const m = time.getMinutes().toString().padStart(2, "0");
    const s = time.getSeconds().toString().padStart(2, "0");
    return `${Y}-${M}-${D} ${h}:${m}:${s}`;
}